package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.Util.SMSRong;
import com.itheima.reggie.Util.ValidateCodeUtils;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.User.Impl.UserServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class Usercontroll {
    @Autowired
    UserServiceImpl userService;

    /**
     * 发送手机验证码
     * @param user
     * @return
     */
    @PostMapping("/yanzhengma")
    public R<String> yanzhengma(@RequestBody User user,HttpServletRequest request){
        //获取手机号
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            //生成验证码
            //String i = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
            //调用阿里云提供的短信服务 API 完成发送短信
            //SMSRong.sendMessage(phone,i);
            //保存 验证码 到
            request.getSession().setAttribute(phone,"1234");
            return R.success("发送成功");
        }
        return R.success("发送失败");
    }
    @PostMapping("/login")
    public R<User> dolong(@RequestBody Map map, HttpServletRequest request){
        log.info("手机号:{}",map.get(""));
        //获取手机号
        String phone = (String) map.get("phone");
        //获取验证码
        String code = (String) map.get("code");
        //从 Session 中获取保存的验证码
        String attribute = (String) request.getSession().getAttribute(phone);
        //进行验证码比对(页面提交的验证码 和 Session 中保存的验证码进行 比对)
        if (code.equals(attribute)){
            //如果能够比对成功 说明登入成功
            LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(User::getPhone,phone);
            User one = userService.getOne(lambdaQueryWrapper);
            if (one == null){
                one = new User();
                one.setPhone(phone);
                one.setStatus(1);
                userService.save(one);
            }
            request.getSession().setAttribute("user",one.getId());
            return R.success(one);
        }
        return   R.error("登入失败");
    }



}
